package com.unicdata.ai.demo_2af.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unicdata.ai.demo_2af.common.entity.Role;
import com.unicdata.ai.demo_2af.common.entity.RolePermission;
import com.unicdata.ai.demo_2af.common.exception.BusinessException;
import com.unicdata.ai.demo_2af.mapper.RoleMapper;
import com.unicdata.ai.demo_2af.mapper.RolePermissionMapper;
import com.unicdata.ai.demo_2af.service.RoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 角色服务实现类
 *
 * @author lhn
 * @date 2025/06/25 16:57
 * @since 1.0.0
 **/
@Service
public class RoleServiceImpl extends ServiceImpl <RoleMapper, Role> implements RoleService {

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public Role getRoleByCode(String roleCode) {
        if (StringUtils.isBlank(roleCode)) {
            return null;
        }

        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Role::getRoleCode, roleCode);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean assignPermissions(Long roleId, List <Long> permissionIds) {
        if (roleId == null) {
            throw new BusinessException("角色ID不能为空");
        }
        if (permissionIds == null) {
            permissionIds = new ArrayList <>();
        }

        // 查询角色是否存在
        Role role = getById(roleId);
        if (role == null) {
            throw new BusinessException("角色不存在");
        }

        // 删除原有权限关联
        LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper <>();
        queryWrapper.eq(RolePermission::getRoleId, roleId);
        rolePermissionMapper.delete(queryWrapper);

        // 添加新权限关联
        if (!permissionIds.isEmpty()) {
            for (Long permissionId : permissionIds) {
                RolePermission rolePermission = new RolePermission();
                rolePermission.setRoleId(roleId);
                rolePermission.setPermissionId(permissionId);
                rolePermission.setCreateTime(new Date());
                rolePermissionMapper.insert(rolePermission);
            }
        }

        return true;
    }
}